package com.topisv.tms.service.account;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.utils.DateProvider;

import com.topisv.tms.entity.Function;
import com.topisv.tms.entity.Permission;
import com.topisv.tms.entity.QueryParamHolder;
import com.topisv.tms.entity.ReturnGood;
import com.topisv.tms.entity.Role;
import com.topisv.tms.entity.User;
import com.topisv.tms.entity.Userrole;
import com.topisv.tms.repository.FunctionDao;
import com.topisv.tms.repository.PermissionDao;
import com.topisv.tms.repository.RoleDao;
import com.topisv.tms.repository.TaskDao;
import com.topisv.tms.repository.UserDao;
import com.topisv.tms.repository.UserroleDao;
import com.topisv.tms.service.ServiceException;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.base.BaseService;
import com.topisv.tms.utils.DigestsUtils;
import com.topisv.tms.utils.enums.StatusEnums;

/**
 * 用户管理类.
 * 
 * @author calvin
 */
// Spring Service Bean的标识.
@Component
@Transactional(readOnly = true)
public class AccountService extends BaseService{

	

	private static Logger logger = LoggerFactory.getLogger(AccountService.class);

	private UserDao userDao;
	private TaskDao taskDao;
	private UserroleDao userroleDao;
	private RoleDao roleDao;
	private PermissionDao permissionDao;
	private FunctionDao functionDao;
	private DateProvider dateProvider = DateProvider.DEFAULT;
	
	public List<User> findByStatus(String status){
		return userDao.findByStatus(status);
	}
	
	public User findByUserId(String userId){
		return userDao.findByUserId(userId);
	}

	public List<User> getAllUser() {
		List<User> users = (List<User>)userDao.findAll();
		for(User user : users)
		{
			List<Role> roles = roleDao.findByUserId(user.getId());
			user.setRoleList(roles);
		}
		return users;
	}
	
	public User getUser(Long id) {
		User user = userDao.findOne(id);
		List<Role> roles = roleDao.findByUserId(id);
		user.setRoleList(roles);
		return user;
	}

	public User findOne(Long id) {
		User user = userDao.findOne(id);
		List<Role> roles = roleDao.findByUserId(id);
		if(StatusEnums.user_type_paiu.getStatus().equals(user.getUserType())){
			List<String> customers=new ArrayList<String>();
			String[] _customers=user.getCustomers()==null? null:user.getCustomers().split(":");
			if(_customers!=null){
				for(String i:_customers){
					customers.add(i);
				}
			}
			
			user.setCustomerLists(customers);
			List<String> areagroups=new ArrayList<String>();
			String[] _areagroups=user.getAreagroups()==null? null:user.getAreagroups().split(":");
			if(_areagroups!=null){
				for(String i:_areagroups){
					areagroups.add(i);
				}
			}
			
			user.setAreagroupLists(areagroups);
		}else{
			List<String> areagroups=new ArrayList<String>();
			String[] _areagroups=user.getAreagroups()==null? null:user.getAreagroups().split(":");
			if(_areagroups!=null){
				for(String i:_areagroups){
					areagroups.add(i);
				}
			}
			
			user.setAreagroupLists(areagroups);
		}
		
		user.setRoleList(roles);
		return user;
	}

	public User findUserByUsername(String loginName) {
		return userDao.findByUsername(loginName);
	}
	
	public User findUserByRealname(String realname) {
		return userDao.findByUsername(realname);
	}
	
	public User findUserByJobuuid(String jobuuid) {
		return userDao.findByJobuuid(jobuuid);
	}
	
	public List<Userrole> findByUserId(Long userid) {
		return userroleDao.findByUser_id(userid);
	}
	
	public List<Userrole> findByRoleName(String userType,List<String> roleName,String areagroups) {
		return userroleDao.findByRoleName(userType,roleName,new StringBuilder().append("%").append(areagroups).append("%").toString());
	} 
	
	public Role findRoleById(Long roleId) {
		return roleDao.findOne(roleId);
	}
	
	public List<Permission> findByRoleId(Long roleId) {
		return permissionDao.findByRoleId(roleId);
	}
	
	public List<Function> getMenu(String status)
	{
		return functionDao.findByStatus(status);
	}

	@Transactional(readOnly = false)
	public void registerUser(User user) {
		DigestsUtils.entryptPassword(user);
		userDao.save(user);
	}
	
	@Transactional(readOnly = false)
	public void save(User user) {
		userDao.save(user);
	}

	@Transactional(readOnly = false)
	public void updateUser(User user) {
		if (StringUtils.isNotBlank(user.getPlainPassword())) {
			DigestsUtils.entryptPassword(user);
		}
		userDao.save(user);
	}

	@Transactional(readOnly = false)
	public void deleteUser(Long id) {
		if (isSupervisor(id)) {
			logger.warn("操作员{}尝试删除超级管理员用户", getCurrentUserName());
			throw new ServiceException("不能删除超级管理员用户");
		}
		userDao.delete(id);
		taskDao.deleteByUserId(id);

	}
	
	@Transactional(readOnly = false)
	public void deleteUser(User user) {
		if (isSupervisor(user.getId())) {
			logger.warn("操作员{}尝试删除超级管理员用户", getCurrentUserName());
			throw new ServiceException("不能删除超级管理员用户");
		}
		user.setStatus("0");
		userDao.save(user);
	}

	/**
	 * 判断是否超级管理员.
	 */
	private boolean isSupervisor(Long id) {
		return id == 1;
	}

	/**
	 * 取出Shiro中的当前用户LoginName.
	 */
	private String getCurrentUserName() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user.username;
	}
	
	/**
	 * 查找商户类型的用户
	 * @param userType 用户类型  paiu：派友用户  customer:商户类型的用户
	 * @param customerCode 商户编码
	 * @return
	 */
	public List<User> loadCustomerTypeUser(String userType, String customerCode) {
		return this.userDao.loadCustomerTypeUser(userType,customerCode);
	}

	
	@Autowired
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@Autowired
	public void setTaskDao(TaskDao taskDao) {
		this.taskDao = taskDao;
	}
	@Autowired
	public void setUserroleDao(UserroleDao userroleDao) {
		this.userroleDao = userroleDao;
	}
	@Autowired
	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}
	@Autowired
	public void setPermissionDao(PermissionDao permissionDao) {
		this.permissionDao = permissionDao;
	}
	
	@Autowired
	public void setFunctionDao(FunctionDao functionDao) {
		this.functionDao = functionDao;
	}

	public void setDateProvider(DateProvider dateProvider) {
		this.dateProvider = dateProvider;
	}

	/**
	 * 获取当前用户
	 * @return
	 */
	public User getCurUser() {
		try {
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			return this.findUserByJobuuid(curUser.jobuuid);
		} catch (Exception e) {
		   return null;
		}
	}
	
	/**
	 * 分页
	 * @param paramHolder
	 * @return
	 */
	public Page<User> getUsers(QueryParamHolder paramHolder) {
		Page<User> users = findByJson(paramHolder, userDao, User.class);
		for(User user : users)
		{
			List<Role> roles = roleDao.findByUserId(user.getId());
			user.setRoleList(roles);
			user.setPassword("");
		}
		return users;
	}
}
